package services

import (
	"fmt"
	"order-validation-api/models"
	"order-validation-api/validators"
	"sync"
)

// OrderValidationService 订单验证服务
type OrderValidationService struct {
	globalValidator   *validators.GlobalValidator
	clientFactory     *validators.ClientValidatorFactory
	mu                sync.RWMutex
}

// NewOrderValidationService 创建新的订单验证服务实例
func NewOrderValidationService() *OrderValidationService {
	generator := &models.DefaultOrderIDGenerator{}
	return &OrderValidationService{
		globalValidator: validators.NewGlobalValidator(generator),
		clientFactory:   validators.NewClientValidatorFactory(),
	}
}

// ValidateOrder 验证单个订单
func (s *OrderValidationService) ValidateOrder(order *models.Order) error {
	// 全局验证
	result := s.globalValidator.ValidateOrder(order)
	if !result.IsValid {
		return fmt.Errorf("global validation failed: %v", result.Errors)
	}

	// 客户端特定验证
	s.mu.RLock()
	clientValidator, err := s.clientFactory.GetValidator(models.ClientType(order.ClientID))
	s.mu.RUnlock()

	if err != nil {
		return fmt.Errorf("unsupported client type: %s", order.ClientID)
	}

	if clientValidator != nil {
		result := clientValidator.ValidateOrder(order)
		if !result.IsValid {
			return fmt.Errorf("client validation failed: %v", result.Errors)
		}
	}

	return nil
}

// ValidateOrderBatch 批量验证订单
func (s *OrderValidationService) ValidateOrderBatch(orders []*models.Order) map[string]error {
	results := make(map[string]error)
	var wg sync.WaitGroup
	var mu sync.Mutex

	// 使用goroutine并发处理以提高性能
	for _, order := range orders {
		wg.Add(1)
		go func(o *models.Order) {
			defer wg.Done()
			err := s.ValidateOrder(o)
			mu.Lock()
			results[o.OrderID] = err
			mu.Unlock()
		}(order)
	}

	wg.Wait()
	return results
}

// GetSupportedClients 获取支持的客户端类型列表
func (s *OrderValidationService) GetSupportedClients() []string {
	s.mu.RLock()
	defer s.mu.RUnlock()
	clientTypes := s.clientFactory.GetSupportedClients()
	result := make([]string, len(clientTypes))
	for i, ct := range clientTypes {
		result[i] = string(ct)
	}
	return result
}

// RegisterClientValidator 注册新的客户端验证器
func (s *OrderValidationService) RegisterClientValidator(validator validators.ClientValidator) {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.clientFactory.RegisterValidator(validator)
}